$(function () {
    var userUrl = "/oa/t-user";
    var roleUrl = "/oa/t-role";
    var token = sessionStorage.getItem('token');
    var oprateFormatter = function (value, row, index) {
        return [
            '<button id="tb_state" class="btn btn-default btn-xs" style="margin: 0 5px 0 5px">启/停用</button>',
            '<button id="tb_edit" class="btn btn-default btn-xs" style="margin: 0 5px 0 5px">编辑</button>',
            '<button id="tb_resetpwd" class="btn btn-default btn-xs" style="margin: 0 5px 0 5px">重置密码</button>',
            '<button id="tb_delete" class="btn btn-default btn-xs" style="margin: 0 5px 0 5px">删除</button>',
        ].join("");
    };

    var oprateEvents = function(context) {
        var me = context;
        return {
            "click #tb_edit" : function(e, value, row, index) {
                me.edit([row]);
            },

            "click #tb_state" : function(e, value, row, index) {
                me.state([row]);
            },

            "click #tb_delete" : function(e, value, row, index) {
                me.remove([row]);
            },

            "click #tb_resetpwd" : function(e, value, row, index) {
                me.resetPwd([row]);
            }
        };
    };

    var stateFormatter = function (value, row, index) {
        if (row.userState == 0) {
            return "停用";
        }else{
            return "启用"
        }
    };

    var roleList = [];
    var roleFormatter = function (value, row, index) {
        var roleData = roleList;
        for (var i = 0; i < roleData.length; i++) {
            var role = roleData[i];
            if (row.roleId == role.roleId) {
                return role.roleName;
            }
        }

        return row.roleId;
    };

    var roleLoader = function (me, field) {
        $(field).empty();
        var elem = $(field);
        var roleData = roleList;
        elem.append('<option value="">请选择角色...</option>');
        for (var i = 0; i < roleData.length; i++) {
            var role = roleData[i];
            elem.append(
                '<option value="'
                + role.roleId
                + '">'
                + role.roleName
                + '</option>'
            );
        }
    };

    var page = $.fn.cookePageTable({
        URL: userUrl,
        dialog: {
            domid: '#addModel',
            title: '用户',
            validate : {
                userName: {
                    required: true,
                },
                userEmail: {
                    required: true,
                    minlength: 4,
                    maxlength: 128,
                    email:true,
                },
                userPhone: {
                    required: true,
                    minlength: 3,
                    maxlength: 19,
                    digits:true,
                },
            },

            fieldLoader: {
                roleId : roleLoader,
            },
        },

        toolbar: {
            add: '#add',
            del: '#del',
            edit: '#edit',
            domid: '#toolbar',
            search: '#search',
        },

        table: {
            domid: "#table",
            uniqueId: "id", //每一行的唯一标识，一般为主键列
            uniqdesc: function(row) {
                return row.userName;
            },                  //每一行的唯一标识描述字段信息
            columns: [{
                checkbox: true
            }, {
                field: 'userName',
                title: '用户名称',
                filter: true,
            }, {
                field: 'roleId',
                title: '角色',
                formatter: roleFormatter,
            }, {
                field: 'userEmail',
                title: '邮箱',
            }, {
                field: 'userPhone',
                title: '电话号码',
            }, {
                field: 'createTime',
                title: '创建时间',
            }, {
                field: 'userState',
                title: '状态',
                formatter: stateFormatter,
            }, {
                field: 'operate',
                title: '操作',
                visible: true,
                events: oprateEvents,
                formatter: oprateFormatter,
            }]
        },
    });

    page.resetPwd = function (arrselections) {
        var me = this;
        if (arrselections.length <= 0) {
            $.message({type:'warning', message:'请勾选要编辑的效数据'});
            return;
        }

        if (arrselections.length > 1) {
            $.message({type:'warning', message:'只能勾选一行进行编辑'});
            return;
        }

        $.ajax({
            type: "post",
            dataType: "json",
            headers: {Token: token},
            url: me.options.URL + '/resetPwd',
            data: JSON.stringify(arrselections[0]),
            contentType: "application/json",
            success: function (data, status) {
                if (data.code != 200) {
                    $.message({type:'error', message:data.msg || data.error});
                    return;
                }

                $.message({type:'success', message:data.msg || data.error});
                me.table.bootstrapTable('refresh');
            },

            error: function (request, status, error) {
                var data = request.responseJSON;
                $.message({type:'error', message:data.msg || data.error});
            },
        });
    }; // end of page.resetPwd

    page.listRole = function (successFun) {
        var me = this;
        $.ajax({
            url: roleUrl + '/listRole?token=' + token,
            type: "GET",
            dataType: "json",
            success: function (data) {
                if (data.code != 200){
                    $.message({
                        message : data.msg || data.error,
                        type:'error'
                    });
                    return;
                }

                if (successFun) {
                    successFun(me, data.data);
                }
            },
        });
    }; // end of page.resetPwd

    page.listRole(function (me, data) {
        roleList = data;
        me.refresh();
    });
});
